/**
 * @author xiao zhou
 * @lastEditTime 2021-06-02 01:55:24
 * @description
 */

const ora = require('ora')
const inquirer = require('inquirer')
const { log, succeed, error, underline } = require('../utils')

module.exports = async (ssh, config, index) => {
  try {
    log(`(${index}) ssh连接 ${underline(config.host)}`)
    const { privateKey, passphrase, password } = config
    if (!privateKey && !password) {
      const answers = await inquirer.prompt([
        {
          'type': 'password',
          'name': 'password',
          'message': '请输入服务器密码'
        }
      ])
      config.password = answers.password
    }

    const spinner = ora('正在连接ssh服务\n')
    spinner.start()

    !privateKey && delete config.privateKey
    !passphrase && delete config.passphrase

    await ssh.connect(config)
    spinner.stop()
    succeed('ssh连接成功')
  } catch (e) {
    error(e)
    // eslint-disable-next-line no-undef
    process.exit(1)
  }
}
